import time
import requests
from common_utils import sendInfo


# 定义一个监控微博函数
def startMonitor(weiboInfo, reqHeaders, itemIds):
    returnDict = {}
    try:
        r = requests.get(weiboInfo, headers=reqHeaders)
        for i in r.json()['data']['cards']:
            if i['card_type'] == 9:
                if str(i['mblog']['id']) not in itemIds:
                    itemIds.append(i['mblog']['id'])
                    # Got a new weibo
                    # @ return returnDict dict
                    returnDict['created_at'] = i['mblog']['created_at']
                    returnDict['text'] = i['mblog']['text']
                    returnDict['source'] = i['mblog']['source']
                    returnDict['nickName'] = i['mblog']['user']['screen_name']
                    # if has photos
                    if 'pics' in i['mblog']:
                        returnDict['picUrls'] = []
                        count = 0
                        for j in i['mblog']['pics']:
                            count += 1
                            returnDict['picUrls'].append('<b>pic_' + str(count) + ' ：</b>' + j['url'] + '<br/>')

                    return returnDict
                    # if i['mblog'].has_key('pics'):
                    #     returnDict['picUrls'] = []
                    #     for j in i['mblog']['pics']:
                    #         returnDict['picUrls'].append(j['url'])
                    #
    except Exception as e:
        print(e)


# 获取首页所有微博的 id
def getItemIds(reqHeaders):
    # 为了获取微博的 ContainerId
    userInfo = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2048344461'
    # response = requests.get(userInfo, headers = reqHeaders)
    # 获取微博 ContainerId
    conId = ''

    try:
        r = requests.get(userInfo, headers=reqHeaders)
        for i in r.json()['data']['tabsInfo']['tabs']:
            if i['tab_type'] == 'weibo':
                conId = i['containerid']
    except Exception as e:
        print(e)

    weiboInfo = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2048344461&containerid=' + conId
    itemIds = []  # 存放首页的所有微博的 id
    # get user weibo index
    try:
        r = requests.get(weiboInfo, headers=reqHeaders)
        for i in r.json()['data']['cards']:
            if i['card_type'] == 9:
                itemIds.append(i['mblog']['id'])
    except Exception as e:
        print(e)

    return itemIds, weiboInfo


if __name__ == '__main__':
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Connection': 'close',
        'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3'
    }

    item_ids, wb_info = getItemIds(headers)
    i = 0
    result = {}

    while 1:
        i += 1
        time.sleep(1)
        result = startMonitor(wb_info, headers, item_ids)
        if result is not None:
            c_tim = result['created_at']
            user = result['nickName']
            text = result['text']
            msg = '<b>博主：</b>' + "".join(user) + '<br/>' + "<b>微博内容：</b><br/>" + text + '<br/>'
            if "picUrls" in result:
                msg = msg + "".join(result['picUrls']) + '<br/>'
            msg += c_tim
            sendInfo("xxxxx@qq.com", msg)       # 收件人账号
        time.sleep(2)
        if i == 180:
            i = 0
            print("监测中..." + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
